package com.link.base.tencent.corpwx.externalcontact.service;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.agent.util.AgentIdUtil;
import com.link.base.tencent.corpwx.externalcontact.util.ExternalContactUtil;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.util.DateUtil;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;
import com.link.base.tencent.corpwx.externalcontact.dao.mybatis.mapper.UnassignedAccountMapper;
import com.link.base.tencent.corpwx.externalcontact.model.UnassignedAccount;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;

import java.util.ArrayList;
import java.util.List;

/**
 * 离职人员客户-离职员工的客户列表 
 *
 * @author 李宗庭
 * @date 2020/01/15 10:21
 */
@Service
public class UnassignedAccountServiceImpl extends BasicServiceImpl<UnassignedAccount> implements UnassignedAccountService {

    @Resource
    private UnassignedAccountMapper unassignedAccountMapper;
    @Resource
    private AgentService agentService;
    
    @Override
    public BasicMapper<UnassignedAccount> getBasicMapper() {
        return unassignedAccountMapper;
    }

    @Override
    public void syncUnassignedAccountFromWx() throws Exception {
        // 获取离职人员的客户
        List<UnassignedAccount> list = getAllUnassignedList(new ArrayList<>(), 0 ,"500");
        // 将离职人员的客户信息保存到CRM
        if (list != null && list.size() > 0) {
            for (UnassignedAccount item : list) {
                UnassignedAccount record = this.getUnassignedFromLink(item);
                if (record == null) {
                    Long id = keyGenerateService.keyGenerate();
                    item.setId(id);
                    unassignedAccountMapper.insert(item);
                } else {
                    item.setId(record.getId());
                    unassignedAccountMapper.update(item);
                }
            }
        }
    }
    
    /** 
    * 递归查询所有离职人员的客户
    * @author Lizongting
    * @date 2020/1/15
    */
    public List<UnassignedAccount> getAllUnassignedList(List<UnassignedAccount> list, int page, String pageSize) throws Exception {
        String accessToken = agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID);
        JSONObject unassignedAccount = ExternalContactUtil.getUnassignedList(accessToken, String.valueOf(page), pageSize);
        boolean isLast = unassignedAccount.getBoolean("is_last");
        JSONArray unassignedList = unassignedAccount.getJSONArray("info");
        if (!isLast) {
            page++;
            list.addAll(analyzingUnassignedAccount(unassignedList));
            getAllUnassignedList(list, page, pageSize);
        } else {
            list.addAll(analyzingUnassignedAccount(unassignedList));
        }
        return list;
    }

    /** 
    * 解析查询到的离职人员的客户信息
    * @author Lizongting
    * @date 2020/1/15
    */
    public List<UnassignedAccount> analyzingUnassignedAccount(JSONArray jSONArray) {
        List<UnassignedAccount> list = new ArrayList<>();
        if (jSONArray != null) {
            for (int i = 0; i < jSONArray.size(); i++) {
                UnassignedAccount item = new UnassignedAccount();
                item.setAccountStatus("unassigned");
                // 时间戳转换为日期格式
                String dismissionTime = jSONArray.getJSONObject(i).getString("dimission_time");
                item.setDimissionTime(DateUtil.unixTimetampToDateString(dismissionTime));
                item.setHandoverUserid(jSONArray.getJSONObject(i).getString("handover_userid"));
                item.setExternalUserid(jSONArray.getJSONObject(i).getString("external_userid"));
                list.add(item);
            }
        }
        return list;
    }

    @Override
    public UnassignedAccount getUnassignedFromLink(UnassignedAccount record) throws Exception {
        if (StringUtils.isBlank(record.getExternalUserid())) {
            throw new BasicServiceException("缺少客户userid信息");
        }
        if (StringUtils.isBlank(record.getHandoverUserid())) {
            throw new BasicServiceException("缺少员工userid信息");
        }
        return unassignedAccountMapper.getUnassignedFromLink(record);
    }

    @Override
    public void reassignAccount(UnassignedAccount record) throws Exception {
        if (StringUtils.isBlank(record.getExternalUserid())) {
            throw new BasicServiceException("联系人客户的userId为空");
        }
        if (StringUtils.isBlank(record.getTakeoverUserid())) {
            throw new BasicServiceException("接替员工的userId参数为空");
        }
        if (StringUtils.isBlank(record.getHandoverUserid())) {
            throw new BasicServiceException("离职员工的userId参数为空");
        }
        // 重新分配离职员工的客户
        String accessToken = agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID);
        ExternalContactUtil.transferExternalContact(accessToken, record.getExternalUserid(),
                record.getHandoverUserid(), record.getTakeoverUserid());
        // 更新离职客户表的状态
        UnassignedAccount queryRecord = unassignedAccountMapper.getUnassignedFromLink(record);
        queryRecord.setTakeoverUserid(record.getTakeoverUserid());
        queryRecord.setAccountStatus("assigned");
        unassignedAccountMapper.update(queryRecord);
    }

}

